package com.android.kotlincoroutinemvvmdemo.contentprovider

import android.content.ContentResolver
import android.content.ContentValues
import android.net.Uri

object GestureDBAction {

    private val URI_GESTURE_DIR =
        Uri.parse("content://${SqlConstant.AUTHORITY_GESTURE}/${SqlConstant.TABLE_GESTURE}")

    private val URI_GESTURE_ITEM =
        Uri.parse("content://${SqlConstant.AUTHORITY_GESTURE}/${SqlConstant.TABLE_GESTURE}/1")


    fun insertValue(resolver: ContentResolver, switch: Int, result: Int) {
        val contentValues = ContentValues()
        contentValues.put(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_SWITCH, switch)
        contentValues.put(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_RESULT, result)
        resolver.insert(URI_GESTURE_DIR, contentValues)
    }

    fun insertValue(resolver: ContentResolver, switch: Int, result: Int, desc: String?) {
        val contentValues = ContentValues()
        contentValues.put(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_SWITCH, switch)
        contentValues.put(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_RESULT, result)
        contentValues.put(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_DESC, desc)
        resolver.insert(URI_GESTURE_DIR, contentValues)
    }

    fun updateValue0(resolver: ContentResolver, switch: Int) {
        val contentValues = ContentValues()
        contentValues.put(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_SWITCH, switch)
        resolver.update(URI_GESTURE_ITEM, contentValues, null, null)
    }

    fun updateValue1(resolver: ContentResolver, result: Int) {
        val contentValues = ContentValues()
        contentValues.put(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_RESULT, result)
        resolver.update(URI_GESTURE_ITEM, contentValues, null, null)
    }

    fun queryValue(resolver: ContentResolver): MutableList<DBEntity> {
        val resultList = mutableListOf<DBEntity>()
        val cursor = resolver.query(URI_GESTURE_DIR, null, null, null, null)
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val id =
                    cursor.getInt(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_ID))
                val switch =
                    cursor.getInt(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_SWITCH))
                val result =
                    cursor.getInt(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_RESULT))
                val desc =
                    cursor.getString(cursor.getColumnIndexOrThrow(SqlConstant.TABLE_GESTURE_COLUMN_GESTURE_DESC))
                resultList.add(DBEntity(id, switch, result, desc))
            }
            cursor.close()
        }
        return resultList
    }

    fun deleteValue(resolver: ContentResolver) {
        resolver.delete(URI_GESTURE_ITEM, null, null)
    }
}